package cn.coco.jf.fw.admin.sys.controller.login;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Clear;

import cn.coco.jf.fw.core.db.SysMenuTbl;
import cn.coco.jf.fw.core.db.SysUserTbl;
import cn.coco.jf.fw.admin.config.consts.SysConfigConst;
import cn.coco.jf.fw.admin.config.consts.SysConsts;
import cn.coco.jf.fw.admin.controller.FwBaseController;
import cn.coco.jf.fw.admin.model.JkUser;
import cn.coco.jf.fw.admin.sys.dao.SysDao;
import cn.coco.jf.fw.admin.sys.dao.login.LoginDao;
import cn.exlu.coco.core.utils.CipherUtil;
import cn.exlu.coco.core.utils.StringUtil;

@Clear
public class LoginController extends FwBaseController {

    public void index(){
    	this.setAttr("userName", this.getCookie("userName", ""));
    	this.setAttr("passwd", this.getCookie("passwd", ""));
    	
    	if(SysConfigConst.SYSTEM_SSO_ABLE) {
    		this.setAttr("ssoAbleFlg", 1);
    		this.render("loginSSO.html");
    		return;
    	}

        this.render("login.html");
    }
    
    /**
     * 解锁
     */
    public void doUnlock(){
        String passwd = getPara("passwd");
        JkUser jkUser = (JkUser)this.getSessionAttr("jkUser");
        
        if(jkUser == null){
            this.errCodeJson(801,"登录过期，请重新登录");
            return;
        }
        
        jkUser = LoginDao.selectNormalByKey(jkUser.getUserCode());
        
        
//        if(!CipherUtil.validatePassword(jkUser.getUserPasswd(), passwd, SysConsts.PASSWORD_KEY)){
        if(!CipherUtil.validatePassword(jkUser.getUserPasswd(), jkUser.getUserCode() + passwd, jkUser.getPasswdSalt())){
            this.errCodeJson(802,"密码错误");
        }else{
            this.successJson(null);
        }
        
    }
    
    /**
     * 解锁
     */
    public void doUpdpasswd(){
        String updpasswdOld = getPara("updpasswdOld");
        String updpasswdNew = getPara("updpasswdNew");
        String updpasswdNewConfirm = getPara("updpasswdNewConfirm");
        JkUser jkUser = (JkUser)this.getSessionAttr("jkUser");
        
        if(jkUser == null){
            this.errCodeJson(801,"登录过期，请重新登录");
            return;
        }
        
        if(StringUtil.isNullOrEmpty(updpasswdOld) || StringUtil.isNullOrEmpty(updpasswdNew) || StringUtil.isNullOrEmpty(updpasswdNewConfirm)){
            this.errCodeJson(802,"请输入密码");
            return;
        }
        
        if(!updpasswdNew.equals(updpasswdNewConfirm)){
            this.errCodeJson(803,"新密码与确认密码要相同");
            return;
        }
        
        if(updpasswdOld.equals(updpasswdNew)){
            this.errCodeJson(804,"原密码与新密码不能相同");
            return;
        }

        jkUser = LoginDao.selectNormalByKey(jkUser.getUserCode());
        
//        if(!CipherUtil.validatePassword(jkUser.getUserPasswd(), passwd, SysConsts.PASSWORD_KEY)){
        if(!CipherUtil.validatePassword(jkUser.getUserPasswd(), jkUser.getUserCode() + updpasswdOld, jkUser.getPasswdSalt())){
            this.errCodeJson(805,"原密码错误");
            return;
        }
        
        SysUserTbl entity = SysUserTbl.dao.findById(jkUser.getUserCode());
        String passwdSalt = StringUtil.createRandomSalt(SysConsts.PASSWD_SALT_LEN);
        entity.setUserPasswd(CipherUtil.generatePassword(entity.getUserCode() + updpasswdNew, passwdSalt));
        entity.setPasswdSalt(passwdSalt);
        
        entity.update();
        this.successJson(null);
        
    }

    /**
     * 用户登录
     */
    @Clear
    public void doLogin(){
         String userName = getPara("userName");
         String passwd = getPara("passwd");
         boolean rememberMe = this.getParaToBoolean("rememberMe", false);
  
         if(!validParmRequire(userName, passwd)){
             renderJson();
             return;
         }

         JkUser jkUser = LoginDao.selectNormalByKey(userName);

         if(jkUser == null){
        	 errJson("用户不存在，或者密码不正确");
             return;
         }
         
         if(StringUtil.isNullOrEmpty(jkUser.getUserPasswd()) || StringUtil.isNullOrEmpty(jkUser.getPasswdSalt()) ) {
    		 errJson("用户不存在，或者密码不正确");
             return;
    	 }
 
    	 if(!CipherUtil.validatePassword(jkUser.getUserPasswd(), jkUser.getUserCode() + passwd, jkUser.getPasswdSalt())){
    		 errJson("用户不存在，或者密码不正确");
    		 return;
    	 }
    	 
		 jkUser.setUserPasswd(StringUtil.BLANK);
		 jkUser.setPasswdSalt(StringUtil.BLANK);
		 
		 List<SysMenuTbl> sysMenuTblList = SysDao.querySysMenuTblListByRoleId(jkUser.getRoleId());
		 List<String> menuUrlList = new ArrayList<String>();
		 String menuUrl = "";
		 for(SysMenuTbl item:sysMenuTblList){
		     menuUrl = item.getMenuUrl();
		     if(!StringUtil.isNullOrEmpty(menuUrl)){
               String[] menuUrls = menuUrl.split(",");
                       for(String url :menuUrls){
                           menuUrlList.add(url);
                       }
                       
                   }
  
        		 }

         // 检索用户菜单
		 jkUser.setMenus(menuUrlList);
		 
		 jkUser.getMenus().add("/");
		 
         setSessionAttr("jkUser", jkUser);
         if(rememberMe){
        	 setCookie("userName", userName, 60 * 24 * 30);

         }else{
             this.removeCookie("userName");
         }

         successJson(null);

    }
    
    /**
     * 用户退出
     */
    public void doLogout(){
//        final JkUser jkUser = (JkUser)getSessionAttr("jkUser");
//        if(jkUser == null){
//            getSession().invalidate();
//            success(null);
//            renderJson();
//        }

        getSession().invalidate();
        success(null);
        renderJson();
    }
    
    
}
